import axios from 'axios';
import router from '../router/index'
const axiosRequest= axios.create({
    withCredentials: true
});
axiosRequest.interceptors.request.use(requestConfig => {
    requestConfig.headers['access_token'] = sessionStorage['access_token'] || ''
    return requestConfig;
});
axiosRequest.interceptors.response.use(response => {
    return new Promise((resolve, reject) => {
        if(!(response.data instanceof Object)) {
            resolve(response);
            return
        }
        if (response.data.code !== 0) {
            /*if(response.data.code === 901 && window.location.pathname !== '/dashboard') {
                console.log(response,'+++++++++++++')
                router.push({name: 'forbidden'});
            }*/
            this.$message.error(response.data.msg)
            reject(response.data)
        }
        resolve(response.data)
    })


},(err) => {
    if(err.response.status === 401) {
        router.push({name: 'forbidden'});
        this.$message.error(err.response.data.msg)
    } else {
        this.$message.error(JSON.stringify(err.response.data))
    }
});
function to(promise) {
    return promise.then(res => [null, res.data, res]).catch(err => [err])
}

const request = (option) => {
    return to(axiosRequest(option))
};
export  {axiosRequest, request}